package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;

/**
 * Title  : 98. Validate Binary Search Tree
 * Source : https://leetcode.cn/problems/validate-binary-search-tree/description/
 * Author : XrazYang
 * Date   : 2023-09-14
 */

public class LeetCode_98 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isValidBST(TreeNode root) {
        ArrayDeque<TreeNode> sta = new ArrayDeque<>();
        TreeNode p = root;
        long max = Long.MAX_VALUE;
        while (p != null || !sta.isEmpty()) {
            while (p != null) {
                sta.push(p);
                p = p.left;
            }
            TreeNode node = sta.pop();
            if (max == Long.MAX_VALUE) {
                max = node.val;
            } else {
                if (max < node.val) {
                    max = node.val;
                } else {
                    return false;
                }
            }
            p = node.right;
        }
        return true;
    }
}
